//
//  IngAnnouncedVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

////设定定时时间为10s
//var countTime =10
//// 在global线程里创建一个时间源
//let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
//// 设定这个时间源是每0.5秒循环一次，立即开始
//codeTimer.scheduleRepeating(deadline: .now(), interval: .milliseconds(500))
//// 设定时间源的触发事件
//codeTimer.setEventHandler(handler: {
//    // 每半秒计时一次
//    countTime = countTime-0.5
//    // 时间到了取消时间源
//    if countTime <= 0{
//        codeTimer.cancel()
//    }
//    // 返回主线程处理一些事件，更新UI等等
//    DispatchQueue.main.async {
//    }
//})
////启动定时器
//codeTime.activate()


import UIKit
import SVProgressHUD

class IngAnnouncedVC: BaseViewController {
    
//    lazy var timer : DispatchSourceTimer = {
    
//    let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
//        
//        
//    codeTimer.scheduleRepeating(deadline: .now(), interval: .milliseconds(1000))
//        
//    codeTimer.setEventHandler(handler: { 
//        
//        QL1(".........")
//        
//            DispatchQueue.main.async {
//                QL1("++++++++")
//
//            }
//    })
//        
//        
//    return codeTimer
//        
//    }()
    
    lazy var timer : Timer = { () -> Timer in
    
        let temp = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(repeats), userInfo: nil, repeats: true)
        
        RunLoop.current.add(temp, forMode: .commonModes)
        
        return temp
    
    }()
    
    var page = -999
    
    var hasmore = "-999"
    
    var dataModels : [DidAnnounModel]?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        timer.fire()

        navigationItem.title = "正在揭晓"
        
        plainTableView.tableFooterView = UIView()
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        plainTableView.separatorStyle = .none
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: IngAnnouncell.self), bundle: nil), forCellReuseIdentifier: IngAnnouncell.identifer())
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        
        plainTableView.mj_header.beginRefreshing()
        
        
        plainTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }
        
        
}
    
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        timer.invalidate()
    }
    
    
    func repeats() {
        
        if dataModels == nil {
            
            QL1("数据还没请求")

            return
        }
        
        if dataModels!.count > 0 {
            
            QL1("开始你的代码-循环,刷新")
            
        } else {
            
            QL1("请求没数据")
        }
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}



extension IngAnnouncedVC{
    
    
    func loadData() {
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["state"] = "2" as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=get_list", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                
                self?.dataModels = [DidAnnounModel]()
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(DidAnnounModel(dic: dic))
                    
                }
                
                
                
                self!.plainTableView.mj_footer.resetNoMoreData()
                
                
                if self?.hasmore == "0" {
                    
                    self!.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }
                
                
                if self!.dataModels!.count == 0{
                    
                    
                    self?.showLogoView(text : "暂无揭晓商品...")
                    
                    
                }
                
                self!.plainTableView.mj_header.endRefreshing()
                
                self!.plainTableView.reloadData()
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
    }
    
    
    func loadMoreData() {
        
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["state"] = "2" as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=get_list", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(DidAnnounModel(dic: dic))
                    
                }
                
                
                
                if self?.hasmore == "0" {
                    
                    self!.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }else{
                    
                    self!.plainTableView.mj_footer.endRefreshing()
                    
                }
                
                
                
                
                self!.plainTableView.reloadData()
                
                
            }else{
                
                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
        
    }
    
}









extension IngAnnouncedVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return 1
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return dataModels?.count ?? 0
        
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let temp = tableView.dequeueReusableCell(withIdentifier: IngAnnouncell.identifer()) as! IngAnnouncell
        
        temp.model = dataModels?[indexPath.row]
        
        return temp
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 140
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        let temp = SurpriseShopDetailVC()
        
        
        temp.odId = dataModels![indexPath.row].od_id
        
        
        navigationController?.pushViewController(temp, animated: true)
        
    }
    
    
    
}


